<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="72px">
      <!-- <el-form-item label="机构名称" prop="parentId">
        <el-input v-model="queryParams.parentId" placeholder="请选择机构" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="机构层级" prop="level">
        <el-input v-model="queryParams.level" placeholder="请输入机构层级" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="上级机构" prop="parentId">
        <el-tree-select v-model="queryParams.parentId" :data="organizationOptions" :props="{
          value: 'organizationId',
          label: 'orgName',
          children: 'children'
        }" value-key="organizationId" placeholder="请选择机构" clearable check-strictly @change="handleQuery" />
      </el-form-item>

      <el-form-item label="机构名称" prop="orgName">
        <el-input v-model="queryParams.orgName" placeholder="请输入机构名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in wdm_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['ruoyi:organization:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表单 -->
    <el-table v-if="refreshTable" v-loading="loading" :data="organizationList" row-key="organizationId"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="序号" width="60px" align="center" type="index" prop="orgId" />

      <el-table-column label="机构名称" align="center" prop="orgName" />

      <!-- <el-table-column label="父机构ID" prop="orgName" /> -->
      <!-- <el-table-column label="机构名称" align="center" prop="orgName" /> -->

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="备注信息" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:organization:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
            v-hasPermi="['ruoyi:organization:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:organization:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改机构信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="organizationRef" :model="form" :rules="rules" label-width="80px">

        <el-card class="box-card">
          <template #header>
            <div class="clearfix" style="text-align: center">
              <span style="font-size: 20px; color: #1890ff">机构基本信息</span>

              <el-form-item label="父机构ID" prop="parentId">
                <el-tree-select v-model="form.parentId" :data="organizationOptions" :props="{
                  value: 'organizationId',
                  label: 'orgName',
                  children: 'children',
                }" value-key="organizationId" placeholder="请选择父机构ID" check-strictly />
              </el-form-item>
              <el-form-item label="机构层级" prop="level">
                <el-input v-model="form.level" placeholder="请输入机构层级, 一级为1, 二级为2..." />
              </el-form-item>
              <el-form-item label="机构名称" prop="orgName">
                <el-input v-model="form.orgName" placeholder="请输入机构名称" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in wdm_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="删除" prop="delFlag">
                <el-radio-group v-model="form.delFlag">
                  <el-radio v-for="dict in del_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>

            </div>
          </template>
        </el-card>

      </el-form>

      <!-- 底部 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Organization">
import {
  listOrganization,
  getOrganization,
  delOrganization,
  addOrganization,
  updateOrganization,
} from "@/api/ruoyi/organization";

const { proxy } = getCurrentInstance();
const { wdm_status, del_flag } = proxy.useDict("wdm_status", "del_flag");

const organizationList = ref([]);
const organizationOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    parentId: null,
    level: null,
    orgName: null,
    status: null,
  },
  rules: {
    parentId: [
      { required: true, message: "父机构ID不能为空", trigger: "blur" },
    ],
    level: [{ required: true, message: "机构层级不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询机构信息列表 */
function getList() {
  loading.value = true;
  listOrganization(queryParams.value).then((response) => {
    // 先过滤已删除数据
    const filteredData = response.data.filter(item => item.delFlag !== "2");
    // 再处理树形结构
    organizationList.value = proxy.handleTree(
      filteredData,
      "organizationId",
      "parentId"
    );
    loading.value = false;
  });
}
// function getList() {
//   loading.value = true;
//   listOrganization(queryParams.value).then((response) => {

//     organizationList.value = proxy.handleTree(
//       response.data,
//       "organizationId",
//       "parentId"
//     );
//     loading.value = false;
//   });
// }

/** 查询机构信息下拉树结构 */
function getTreeselect() {
  listOrganization().then((response) => {
    organizationOptions.value = [];
    // 先过滤已删除数据
    const filteredData = response.data.filter(item => item.delFlag !== "2");
    
    const data = { 
      organizationId: 0, 
      orgName: "顶级节点", 
      children: [] 
    };
    // 使用过滤后的数据构建树
    data.children = proxy.handleTree(
      filteredData,
      "organizationId",
      "parentId"
    );
    organizationOptions.value.push(data);
  });
}
// function getTreeselect() {
//   listOrganization().then((response) => {
//     organizationOptions.value = [];
//     const data = { organizationId: 0, orgName: "顶级节点", children: [] };
//     data.children = proxy.handleTree(
//       response.data,
//       "organizationId",
//       "parentId"
//     );
//     organizationOptions.value.push(data);
//   });
// }

/** 树形结构处理 */
function processTreeData(data) {
  const filteredData = data.filter(item => item.delFlag !== "2");
  return proxy.handleTree(filteredData, "organizationId", "parentId");
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    organizationId: null,
    parentId: null,
    level: null,
    orgName: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("organizationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.organizationId) {
    form.value.parentId = row.organizationId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加机构信息";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getOrganization(row.organizationId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改机构信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["organizationRef"].validate((valid) => {
    if (valid) {
      if (form.value.organizationId != null) {
        updateOrganization(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrganization(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除机构信息编号为"' + row.organizationId + '"的数据项？')
    .then(function () {
      return delOrganization(row.organizationId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/* 页面加载时执行方法 */

// 获取机构信息列表
getList();
// 获取机构信息下拉树结构
getTreeselect();
</script>
